<?php
namespace common\components\user;

use common\components\BaseComponent;
use admin\models\user\User;
use common\helpers\ShowFunction;
use common\helpers\ErrorHelper;

/**
 * 通行证用户信息组件
 * @author oneday
 *
 */
class adminUserComponent extends BaseComponent
{
    // user表存在查询的字段
    public $USER_FETCH_COLUMN_LIST = array('id', 'username');
    
    /**
     * 根据指定字段条件，获取用户信息
     * @param $column
     * @param $value
     * @return array|mixed
     */
    public function getUserInfoByColumn($column, $value)
    {
        if (empty($column) || empty($value)) {
            return array();
        }
        if (!in_array($column, $this->USER_FETCH_COLUMN_LIST)) {
            return array();
        }
        
        $userInfoObj = User::findOne(array($column => $value));
        if (empty($userInfoObj)) {
            return array();
        }
        $userInfo = $userInfoObj->attributes;
        return $userInfo;
    }
    
    
    /**
     * 更新指定条件的一条用户信息
     * @param array $condition  where条件数组
     * @param array $updateData 更新的字段和值数组
     * @return bool
     */
    public function updateUserInfo($condition, $updateData)
    {
        if (empty($condition) || empty($updateData)) {
            return false;
        }
        
        $userInfoModel = User::findOne($condition);
        if (empty($userInfoModel)) {
            $this->setError("用户信息不存在");
            return false;
        }
        
        foreach($updateData as $key=>$val){
            $userInfoModel->$key = $val;
        }
        if (isset($updateData['password'])) {
            $dealPassword = User::generateMd5Password($updateData['password']);
            $userInfoModel->password = $dealPassword;
            // 修改了密码，必须重新生成password_hash
            $userInfoModel->password_hash = \Yii::$app->security->generatePasswordHash($dealPassword);
        }
        $userInfoModel->save();
        
        return true;
    }
    
    /**
     * 添加账户信息
     * @param string $username      账户名
     * @param string $password      原文密码
     * @return boolean
     */
    public function createUser($username, $password)
    {
        $error = ErrorHelper::get('paramsError');
        if (empty($username) || empty($password)) {
            $error['message'] = '参数错误';
            $this->setError($error);
            return false;
        }
        
        $dealPassword = User::generateMd5Password($password);
        $nowTime = date("Y-m-d H:i:s");
        
        $userObj = new User();
        $userObj->username = $username;
        // 生成password_hash
        $userObj->password_hash = \Yii::$app->security->generatePasswordHash($dealPassword);
        $userObj->password = $dealPassword;
        $userObj->login_token = \Yii::$app->security->generateRandomString() . '_' . time();
        $userObj->last_login_ip = ShowFunction::realIp();
        $userObj->last_login_time = $nowTime;
        $userObj->status = User::STATUS_INACTIVE;
        $addRes = $userObj->save();
        if (empty($addRes)) {
            $error['message'] = $userObj->getErrors();
            $this->setError($error);
            return false;
        }
        return $userObj;
    }
    
    
    /**
     * 通过uid，完成yii框架的登录流程
     * @param int $uid          登录用户uid
     * @return boolean
     */
    public function loginByUid($uid)
    {
        $userModel = User::findOne(['id' => $uid]);
        if (empty($userModel)) {
            $this->setError(ErrorHelper::get('userError'));
            return false;
        }
        if (!User::isPasswordResetTokenValid($userModel->login_token)) {
            // access_token校验失败，重新生成
            $userModel->generatePasswordResetToken();
            // 更新user的access_token
            $userModel->save(false);
        }
        
        $loginRes = \Yii::$app->user->login($userModel);
        if ($loginRes == false) {
            $this->setError(ErrorHelper::get('loginError'));
            return false;
        }
        return $userModel;
    }


    /**
     * 批量获取多个uid的用户详细信息列表
     * @param array $uid    数组形式
     * @return array
     */
    public function findByUids($uids)
    {
        if (empty($uids)) {
            return array();
        }
        if(!is_array($uids)){
            return array();
        }
        $uids = array_unique($uids);
        $userList = User::find()->where(['id'=>$uids])->asArray()->all();
        if (empty($userList)) {
            return array();
        }
        return $userList;
    }

}